package com.backmanage.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.engine.query.spi.ParameterParser.Recognizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.backmanage.entity.A;
import com.backmanage.entity.User;

/**
 * @author tangjiang 
 * 类说明
 * @param <T>
 */
@SuppressWarnings("all")
@Repository
public  class BaseDao<T> implements BaseDaoI{
	
	@Override
	public <T> void saveOrUpdate(T o) {
		getSession().saveOrUpdate(o);
	}

	@Override
	public <T> void batchSaveOrUpdate(List<T> entitys) {
		for (T t : entitys) {
			getSession().saveOrUpdate(t);
		}
	}

	@Override
	public <T> void delete(T o) {
		getSession().delete(o);
	}

	@Override
	public <T> T get(Class<T> classType, Serializable id) {
		return (T)getSession().get(classType, id);
	}

	@Override
	public <T> List<T> getByProperty(Class<T> classType, String propertyName,
			Object value) {
		Criteria criteria = getSession().createCriteria(classType);
		return criteria.add(Restrictions.eq(propertyName, value)).list();
	}

	@Override
	public <T> List<T> getByProperty(Class<T> classType, Map<String, ?> map) {
		
		Criteria criteria = getSession().createCriteria(classType);
		
		for (String key : map.keySet()) {
			if(map.get(key)!=null){
				criteria.add(Restrictions.eq(key, map.get(key)));
			}
		}
		return criteria.list();
	}	
	private Class<T> entityClass;
	
	@Resource
	private SessionFactory sessionFactory;
	
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@SuppressWarnings({"rawtypes","unchecked"})
	public BaseDao() {
		Type genType = getClass().getGenericSuperclass();
		if (genType instanceof ParameterizedType) {
			Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
			entityClass = (Class) params[0];
		}else{
			
		}
	}

}
